package br.usp.ime.controllers;

import java.util.List;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.usp.ime.components.WebUser;
import br.usp.ime.components.daos.TopicDao;
import br.usp.ime.entities.Topic;

@Resource
public class TopicController {
	
	
	private WebUser webUser;
	private Result result;
	private TopicDao topicDao;

	public TopicController(WebUser webUser, Result result, TopicDao topicDao) {
        this.webUser = webUser;
		this.result = result;
		this.topicDao = topicDao;
	}
	
	@Get("/topics")
    public List<Topic> topics() {
        result.include(webUser);
        return topicDao.listAllTopics();
    }
    
	@Get("/listTopics")
    public List<Topic> listTopics() {
        result.include(webUser);
        return topicDao.listAllTopics();
    }
    

    @Get("/topic/new")
    public void newTopicForm(WebUser webUser) {
    }

    @Post("/topic/new")
    public void newTask(Topic topic) {
        if (topic != null) {
            topicDao.addTopic(topic);
        }
        result.redirectTo(TopicController.class).topics();
    }
    
    @Post("/topic/delete")
    public void deleteTopic(Topic topic) {
       topicDao.deleteTopic(topic);
        result.redirectTo(TopicController.class).topics();
    }
    
    @Get("/topic")
    public void editTopic(Topic topic) {
        Topic loadedTopic = topicDao.loadTopic(topic);
        result.include(loadedTopic);
        result.include(webUser);
    }
    
    @Put("/topic")
    public void updateTopic(Topic topic) {
    	if(topic == null) {
            result.redirectTo(TopicController.class).topics();
            return;
    	}
        Topic loadedTopic = topicDao.loadTopic(topic);
        loadedTopic.copyTask(topic);
        topicDao.updateTopic(loadedTopic);
        result.redirectTo(TopicController.class).topics();
    }
    
}
